import { NextRequest, NextResponse } from 'next/server';
import { PeriodService } from '@/services/periodService';

export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const userId = searchParams.get('user_id');
    const year = searchParams.get('year') ? parseInt(searchParams.get('year')!) : undefined;
    const month = searchParams.get('month') ? parseInt(searchParams.get('month')!) : undefined;

    if (!userId) {
      return NextResponse.json(
        { code: 400, error: '缺少用户ID' },
        { status: 400 }
      );
    }

    const periods = await PeriodService.getPeriods(userId, year, month);
    return NextResponse.json({ code: 200, data: periods });
  } catch (error) {
    console.error('GET periods error:', error);
    return NextResponse.json(
      { code: 500, error: '获取经期记录失败' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const data = await request.json();
    
    if (!data.user_id || !data.start_date) {
      return NextResponse.json(
        { code: 400, error: '缺少必要参数' },
        { status: 400 }
      );
    }

    const period = await PeriodService.createPeriod({
      user_id: data.user_id,
      start_date: new Date(data.start_date),
    });

    return NextResponse.json({ code: 200, data: period });
  } catch (error) {
    console.error('POST period error:', error);
    return NextResponse.json(
      { code: 500, error: '创建经期记录失败' },
      { status: 500 }
    );
  }
} 